import * as api from '@/services/deploy';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { Button,  Col,  Row,  } from 'antd';
import React, { useRef, useState } from 'react';
// import * as c from '@/services/consts';
import { EditableProTable, ProColumns,  ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { useModel } from 'umi';
import VpnServerForm from '../VpnServer/components/VpnServerForm';
import VpnServerBatchForm from '../VpnServer/components/BatchVpnServerForm';
import { PlusOutlined } from '@ant-design/icons';

type DeployFormProps = {
  visible: boolean;
  servers: API.VpnServerMonitorModel[] | undefined;
  onCancel: () => void;
  onSubmit: () => void;
};

const DeployForm: React.FC<DeployFormProps> = (props) => {
  const { visible, servers, onCancel, onSubmit } = props;

  if (!visible) {
    return null;
  }

  const { hasRight } = useModel('useAuthModel');
  
  const { getDeployConfigOptions, getVpnGroupTitle } = useModel('useGlobalModel', (model) => ({
    // getVpnGroupExTrees: model.getVpnGroupExTrees,
    // suppliers: model.suppliers,
    getDeployConfigOptions: model.getDeployConfigOptions,
    getVpnGroupTitle: model.getVpnGroupTitle,
  }));

  const formRef = useRef<ProFormInstance>();
  // const editorFormRef = useRef<EditableFormInstance<API.VpnServerNet>>();


  const [formVpnServerVisible, setFormVpnServerVisible] = useState<boolean>(false);
  const [formBatchVisible, setFormBatchVisible] = useState<boolean>(false);
  const [serverEditableKeys, setServerEditableKeys] = useState<React.Key[]>(() => servers?.map((item) => item.instanceId),);
  const [addServers, setAddServers] = useState<API.VpnServer[]>([]);
  const [addServerEditableKeys, setAddServerEditableKeys] = useState<React.Key[]>([]);

  

  const handleFormSubmit = async (record: API.DeployForm) => {    
    record.creates = addServers;
    record.instanceIds = servers?.map((item) => item.instanceId);
    // console.log(record);
    const result = await api.add(record);
    if (result && result.success) {
      onSubmit();
    }
  };
  
  const handleVpnServer = (record: API.VpnServer) => {
    let ds = addServers.concat(record);
    // console.log(record, ds); 
    setAddServers(ds);
    setAddServerEditableKeys(() => ds?.map((item) => item.instanceId));
    setFormVpnServerVisible(false);
  };
  
  const handleFormBatchSubmit = (records: API.VpnServer[]) => {
    let ds = addServers.concat(records);
    // console.log(record, ds); 
    setAddServers(ds);
    setAddServerEditableKeys(() => ds?.map((item) => item.instanceId));
    setFormBatchVisible(false);
  };
  
  // const getActionOptions = () => {
  //   let options = getDeployConfigOptions(1);
  //   return options.map((element) => {
  //     return {label:element.label, value: element.value};
  //   });
  // }
  
  // const getPackageOptions = () => {
  //   let options = getDeployConfigOptions(4);
  //   return options.map((element) => {
  //     return {label:element.label, value: element.value};
  //   });
  // }
  
  const loadDataNet = async (params: any,sort: any,filter: any,) => {
    return { ...params, data: addServers };
  };


  const serverColumns: ProColumns<API.VpnServerMonitorModel | API.VpnServer>[] = [
    {
      title: '实例ID',
      dataIndex: 'instanceId',
      readonly: true,
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'name',
      readonly: true,
    },
    {
      title: '分组',
      dataIndex: 'groupIds',
      readonly: true,
      renderText:(val) =>{
        return getVpnGroupTitle(val);
      }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];


  return (
    <DrawerForm<API.DeployForm>
      open={visible}
      title='部署服务器'
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      // submitter={{
      //   render: (props, defaultDoms) => {
      //     return [defaultDoms[0]];
      //   },
      // }}
      // loading={myloading}
    >
      <Row gutter={24} style={{marginTop:10}}>
        <Col span={8}>
          <ProFormText
            name="name"
            label="名称"
            initialValue={name}
          />
        </Col>
        <Col span={5}>
          <ProFormSelect
            name='action'
            label="操作"
            allowClear={false}
            options={getDeployConfigOptions(1)}
            mode='single'
            rules={[{ required: true, message: '请选择操作动作' }]}
            fieldProps={{
              listHeight:600
            }}
          />
        </Col>
        <Col span={5}>
          <ProFormSelect
            name='package'
            label="VpnServer安装包"
            allowClear={true}
            options={getDeployConfigOptions(4)}
            mode='single'
          />
        </Col>
        <Col span={5}>
          <ProFormSelect
            name='packageHelper'
            label="Helper安装包"
            allowClear={true}
            options={getDeployConfigOptions(5)}
            mode='single'
          />
        </Col>
      </Row>      
      <Row>
        <Col span={24} style={{marginBottom:-20}}>
          <ProFormTextArea name="remark" label="备注" />
        </Col>
      </Row>

       
      <Row gutter={24}>
        <Col span={24}>
          <EditableProTable<API.VpnServer>
            rowKey="instanceId"
            headerTitle={<span style={{color:'#D48806',marginTop:20}}><b>新增服务器</b></span>}
            locale={{ emptyText: '暂无数据' }}
            columns={serverColumns}
            defaultValue={addServers}
            recordCreatorProps={false}
            onChange={(value: API.VpnServer[]) => {
              // console.log(value);
              setAddServers(value);
            }}
            editable={{
              type: 'multiple',
              editableKeys: addServerEditableKeys,
              actionRender: (row, config, defaultDom) => [
                defaultDom.delete,
              ],
              onValuesChange: (record, recordList) => {
                // console.log(record, recordList);
                setAddServers(recordList);
              },
              onChange: setAddServerEditableKeys,
            }}
            toolBarRender={() => {
              var toolbarDoms: any[] = [];    
              if (hasRight('vpnserver_create')) {
                toolbarDoms.push([
                  <Button
                    type="primary"
                    key="createBatch"
                    onClick={() => {
                      setFormBatchVisible(true);
                    }}
                  >
                    <PlusOutlined />
                    批量新建
                  </Button>,
                  <Button
                    type="primary"
                    key="create_check_manual"
                    onClick={() => {
                      setFormVpnServerVisible(true);
                    }}
                  >
                  <PlusOutlined />
                   新建
                  </Button>
                ]);
              }
              return toolbarDoms;
            }}
            // dataSource={addServers}
            request={loadDataNet}
            params={{ds: addServers}}
          />
        </Col>
      </Row>
      
      {servers ? 
      <Row gutter={24}>
        <Col span={24}>
          <EditableProTable<API.VpnServerMonitorModel | API.VpnServer>
            rowKey="instanceId"
            headerTitle={<span style={{color:'#D48806',marginTop:20}}><b>选中服务器</b></span>}
            locale={{ emptyText: '暂无数据' }}
            columns={serverColumns}
            defaultValue={servers}
            recordCreatorProps={false}
            editable={{
              type: 'multiple',
              editableKeys: serverEditableKeys,
              actionRender: (row, config, defaultDom) => [
                defaultDom.delete,
              ],
              onChange: setServerEditableKeys,
            }}
          />
        </Col>
      </Row>
      : ''}


      <VpnServerForm
        visible={formVpnServerVisible}
        loadNodeId={undefined}
        defaultGroupIds={undefined}
        onSubmit={undefined}
        onSubmitReturn={handleVpnServer}
        onCancel={() => {
          setFormVpnServerVisible(false);
        }}
      />
      <VpnServerBatchForm
        visible={formBatchVisible}
        onSubmit={undefined}
        onSubmitReturn={handleFormBatchSubmit}
        onCancel={() => {
          setFormBatchVisible(false);
        }}
      />

    </DrawerForm>
  );
};

export default DeployForm;
